Control Structures specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is true and optionally, other statements to be executed if the condition is false.
See blow image to understand control (Decision making ) structure:-
C programming language assumes any zero and null values as false, and if it is either non-zero or non-null, then it is assumed as true value.
C programming language provides the following types of decision making statements.
If Statement OR If-else Statements:
Both an ‘if’ and ‘if-else’ are available in C. The <expression> can be any valid expression. The parentheses around the expression are not required, if it is just a single expression.
2 3 4 5 6 7 8 9 10 |
if(<expression>) <statement> // simple form with no {}'s or else clause if(<expression>) { // simple form with {}'s to group statements <statement> <statement> } |
2 3 4 5 6 7 8 9 10 11 |
if(<expression>) // full if/else form { <statement> } else { <statement> } |
Conditional Expression -or- The Ternary Operator:
The conditional expression can be used as a shorthand for some if-else statement. The general syntax of the conditional operator is:
<expression1> ? <expression2> : <expression3>
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
if (x < y) { min = x; }else { min = y; } You just say... min = (x < y) ? x: y; |
Switch Statement:
The switch statement is a sort of specialized form of if used to efficiently separate different block of code based on the value of an integer. The case expressions are typically ‘int’ or ‘char’ constants, The switch statement is probably the single most syntactically awkward and error-prone features of the C language.
switch (<expression>) {
case <const-expression-1>:
<statement>
break;
case <const-expression-2>:
<statement>
break;
case <const-expression-3>: // here we combine case 3 and 4
case <const-expression-4>:
<statement>
break;
default: // optional
<statement>
Each constant needs its own case keyword and a trailing colon (:). Once execution has jumped to a particular case, the program will keep running through all the cases from that point down— this so called “fall through” operation is used in the above example so that expression-3 and expression-4 run the same statements. The explicit break statements are necessary to exit the switch.
Pradeep Maurya is the Professional Web Developer & Designer and the Founder of “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co